import axios from 'axios';
import { message as antMsg } from "antd";
import { getCookie } from "@/utils";

// axios基本设置
axios.defaults.baseURL = '/college';
axios.defaults.timeout = 30000;
axios.defaults.withCredentials = true;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";

// request拦截器
axios.interceptors.request.use(
    (req) => {
        const token = getCookie('USER_TOKEN');
        if(token){
            req.headers['Authorization'] = "bearer " + token;
        }
        return req
    }, (err) => {
        return Promise.reject(err)
    });

// response拦截器
axios.interceptors.response.use(
    (res) => {
        if(res.status === 200){
            return res.data
        }
        return res
    }, (err) => {
        const { response } = err;
        switch (response.status) {
            case 401: {
                if(response.data && response.data.error === "invalid_token"){
                    antMsg.warning("登录信息已过期，请重新登录");
                    window.location.href = "/login?redirect=" + encodeURIComponent(window.location.pathname + window.location.search)
                }else{
                    antMsg.error((response.data && response.data.error) || '未知错误，请重试');
                }
                break;
            }
            default: {

            }
        }
        return Promise.reject(err)
    });


export default axios;